<?php
declare (strict_types = 0);
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\Cache;
use app\model\CustomerModel;
use app\model\UserModel;
use app\model\DeptModel;
use app\Common;
use app\controller\Login;
use app\controller\Token;
use app\controller\Dept;
use app\controller\Sms;


class Customer{
    //常用数据表内容 及常用字典
    var $back = "<script>setTimeout(function(){history.back();},3000)</script>";
    var $dept=[];
    var $users=[];
    var $sex=[0=>'未知',1=>'男',2=>'女'];
    var $type = array('1'=>'顾客',2=>'店家');
    var $status=array('1'=>'正常','2'=>'关闭','3'=>'黑名单');
    var $levels=array(0=>'','1'=>'★','2'=>'★★','3'=>'★★★','4'=>'★★★★','5'=>'★★★★★');
    var $t_levels=array(0=>'未评级',5=>'五级教练员',4=>'四级教练员',3=>'三级教练员',2=>'二级教练员',1=>'一级教练员');
    var $train_type = array(1=>'C1',2=>'C2',3=>'D',4=>'E',5=>'F');
    var $acc_type=array(1=>'学费(收款)',2=>'补考费(收款)',3=>'其他收款',4=>'普通红包',5=>'推广红包',6=>'订单结算/其它付款',7=>'提现');    


    public function __construct(){
        $um=new UserModel();
        $this->users = $um->getAll();
        
        $dm=new DeptModel();
        $this->dept = $dm->getAll();

    }

    //找一人
    public function getOne($name_or_mobile=''){
        $uid=Session::get('logonid');
        if(!$name_or_mobile && empty($uid)) return header("location:/index.php/login/index/target/admin");  

        $all=Request::param(); 

        if(!empty($all['id'])){
            $row=Db::table('customer')->find($all['id']);
            if($row){
                return json(['code'=>1,'data'=>$row,'msg'=>'找到会员,编号：'.$row['id']]);
            }
            return json(['code'=>0,'msg'=>'没找到任何信息.']);
        }

        //后台传参数查询
        if($name_or_mobile){
            $nm = trim($name_or_mobile); 
            $row = Db::query('select * from customer where name=? or mobile=?',[$nm,$nm]);
            if(!count($row)) return ['code'=>0,'msg'=>'查无此人,手机:'.$name_or_mobile];
            return ['code'=>1,'data'=>$row[0]];
        }

        if(!empty($all['nameOrMobile'])){
            $nm = trim($all['nameOrMobile']); 
            $row = Db::query('select * from customer where name=? or mobile=?',[$nm,$nm]);
            if(!count($row)) {
                return json(['code'=>0,'msg'=>"【".$all['nameOrMobile']."】未找到相关人员!"]);
            }

            $row[0]['level_name']=$this->levels[$row[0]['level']];
            return json(['code'=>1,'data'=>$row[0],'msg'=>'人员找到，姓名：'.$row[0]['name'].',编号：'.$row[0]['id']]);
        }

        return json_encode(['code'=>0,'msg'=>'没找到任何信息！']);

    }

    //教练或学员列表接口
    public function customer_list(){
        $all=Request::param();
        $cust = Db::table('customer')->where('status',1);

        if(!empty($all['name_or_mobile'])) {
            $cust ->whereRaw("name like '%".trim($all['name_or_mobile'])."%' or mobile like '%".trim($all['name_or_mobile'])."%'");
        }

        $type = empty($all['type'])?2:$all['type'];
        $cust->where('type','in',$type);

        $dept_id='';
        if(!empty($all['dept_id'])){
            $dept_id =$all['dept_id'];
            $cust->where('dept_id',$dept_id);
        }

        $list=$cust->select()->toArray(); 

        foreach($list as &$kv){
            $kv['image'] = empty($kv['image'])?'/upload/logo.png':$kv['image'];            
        }

        return json(['code'=>1,'msg'=>['rows'=>count($list)],'data'=>$list]);
    }

    public function index(){
        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index.php/login/index/target/admin");

        $all=Request::param();
        $type=!empty($all['type'])?$all['type']:'1,12,24,36,48';
        $view = $type==2?'trainer_list':'index';
        $type_name = $type==2?'店家':'顾客';
        $page_limit=20;
        $show_grid=0;

        if(!empty($all['show_grid'])){
            $page_limit=10;
            $show_grid=$all['show_grid'];
        }
        $list = Db::table("customer")->where('type','in',$type);


        //部门权限
        $dept = new dept();
        $my_depts = $dept->getMyDepts($uid);
        $arr =[];
        $dept_id='';
        foreach($my_depts as $dept){$arr[]=$dept['id'];}
        if(!empty($all['dept_id'])){
            $dept_id=$all['dept_id'];
            if(in_array($dept_id,$arr)){
                $arr=[$dept_id];
            }else{
                $arr=[];
            }
        }
        $my_depts = implode(",",$arr);
        $list->where('dept_id','in',$my_depts);

        //名字
        $name='';
        if(!empty($all['name'])){
            $name = trim($all['name']);
            $list = $list->where('name','like','%'.$name.'%');
        }
        
        $mobile="";
        if(!empty($all['mobile'])){
            $mobile = trim($all['mobile']);
            $list = $list->where('mobile','like','%'.$mobile.'%');
        }

        $list = $list->order('update_time','desc')->paginate($page_limit)->toArray();
        //halt($this->cars);

        foreach($list['data'] as &$kv){
            $kv['type_name'] = $this->type[$kv['type']];
            $kv['creater_name'] = $this->users[$kv['creater']]['name'];
            $kv['inviter_name'] =!empty($kv['inviter'])? Db::table('customer')->where('id',$kv['inviter'])->value('name'):'';
            $kv['sex'] = $this->sex[$kv['sex']];
            $kv['age'] =  (int)((time()-strtotime($kv['birth_date']))/3600/24/365);
            $kv['dept_id_name'] =$kv['dept_id']>0? $this->dept[$kv['dept_id']]['name'] :'';            
            $kv['mobile2'] = substr($kv['mobile'],0,3).'****'.substr($kv['mobile'],7,4); //134 1234 1234
            $kv['image'] = empty($kv['image'])?'/upload/logo.png':$kv['image'];
            $kv['money_check']=md5($kv['create_time'].$kv['money'])==$kv['money_v']?'':'金额异常';
            $kv['status_name']=$this->status[$kv['status']];
        }

        $shop_list=Db::table('dept_info')->where('status',1)->column('id,name');
        //halt($list);
        View::assign(
            array(
                'list'=>$list,
                'type_name'=>$type_name,
                'types'=>$this->type,
                'name'=>$name,
                'dept_id'=>$dept_id,
                'mobile'=>$mobile,
                'status'=>$this->status,
                'show_grid'=>$show_grid,
                'shop_list'=>$shop_list
            )
        );
        return View::fetch($view);
    }  

    /*
    *状态改变,推广费记账
    *
    */
    public function status_update(){
        $uid=Session::get('logonid');
        if(empty($uid)) return json(['code'=>0,'msg'=>'fail1']);

        $all = Request::param();
        if(empty($all['cid'])) return json(['code'=>0,'msg'=>'fail2']);
        if(empty($all['status']) || empty($this->status[$all['status']])) return json(['code'=>0,'msg'=>'fail3']);

        $id=$all['cid'];

        $customer = new CustomerModel();
        $row =$customer->find($id);

        //更新客户
        $cust= array('id'=>$row['id'],'status'=>$all['status'],'update_time'=>date('Y-m-d H:i:s'));
        if($all['status']==5){
            $cust['grad_time'] = $cust['update_time'];
        }
        $res =$customer->update($cust);
        if(!$res) json(['code'=>0,'msg'=>'状态无更新！']);

        return json(['code'=>1,'msg'=>'状态更新！']);

    }



    //会员编辑方法
    public function edit(){
        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index.php/login/index/target/admin");

        $all = Request::param(); 

        if(empty($all['id'])) return 'Invalid member id!'.$this->back;
        $id=$all['id'];

        $type=!empty($all['type'])?$all['type']:'1,12,24,36,48';
        $view = $type==2?'trainer_edit':'customer_edit';

        $customer = new CustomerModel();
        $row =$customer->find($id);

        //传入内容,保存数据并跳转
        if(!empty($all['mobile']) && !empty($all['name'])){
            //halt($row);
            if(strlen($all['id_card'])==18){
                $idc=substr($all['id_card'],6,8);
                $all['birth_date'] =substr($idc,0,4)."-".substr($idc,4,2)."-".substr($idc,6,2);
            }

            $all['update_time'] = date('Y-m-d H:i:s');
            if(empty($all['dept_id'])) $all['dept_id']=1;

            $check = $this->input_check($all);
            if(!$check['code']){
                return $check['msg'].$this->back;
            }

            //跟进记录处理
            if(!empty($all['follow_memo'])){
                $follow=array(
                    'customer_id'=>$row['id'],
                    'user_id'=>$uid,
                    'memo'=>$all['follow_memo'],
                    'create_time'=>date('Y-m-d H:i:s')
                );
                Db::table('follow_log')->insert($follow);
            }

            unset($all['follow_memo']); //halt($row['dept_id']==$all['dept_id'],$row['trainer']==$all['trainer']);
            //保存
            Db::table('customer')->save($all);
            $loc= 'location:/index.php/customer/index/';
            $loc.=($type==2)?'type/2':'';

            //删除旧照片
            if(!empty($_FILES['file']['size'])){
                if($row['image']) Common::rm_file($row['image']);
            }

            //分配记录处理
            // if($row['type'] !=2){
            //     if($all['dept_id']!=$row['dept_id'] || $all['trainer']!= $row['trainer']){
            //         $allocate_log=array(
            //             'customer_id'=>$row['id'],
            //             'dept_id'=>$all['dept_id'],
            //             'user_id'=>$uid,
            //             'memo'=>'修改资料',
            //             'create_time'=>date('Y-m-d H:i:s')
            //         );
            //         Db::table('allocate_log')->insert($allocate_log);
            //     }
            // }

           // return header($loc);
        }

        //不传内容只有id,查出本条数据 并进入编辑
        $row = $customer->find($id);
        $row['inviter_name'] = Db::table('customer')->where('id',$row['inviter'])->value('name');
        if(!$row['image']){
            $row['image']='/upload/logo.png';
        }
        $row['status_name']= $this->status[$row['status']];
        
        $user = Db::table('user')->find($uid); 

        View::assign([
            'status'=>$this->status,
            'type'=>$this->type,
            'data'=>$row,
            'status'=>$this->status,
            'user'=>$user

        ]);
        return View::fetch($view);
    }


    //会员注册新增
    public function register(){
        $all = Request::param();

        if(empty($all['mobile'])) return json(['code'=>0,'msg'=>'无效手机号码!']);
        if(!empty($all['inviter']) && $all['inviter']==$all['mobile']) return json(['code'=>0,'msg'=>'自己邀请自己是不对的哦!']);

        $mobile = Common::is_mobile($all['mobile']);
        if(!$mobile) {
            return json(['code'=>0,'msg'=>'手机号码不正确！']);
        }

        //----------短信验证码-----------------------------------//
        if(empty($all['verify_code'])){//
            return json(['code'=>0,'msg'=>'请输入验证码！']);
        }

        $sess_vcode=Cache::get($all['mobile']);
        if(empty($sess_vcode)){
            return json(['code'=>0,'msg'=>'请先获取验证码！']);
        }

        if($all['verify_code']!=$sess_vcode) {
            return json(['code'=>0,'msg'=>'验证码错误！']);
        }
        //----------短信验证码------------------------------------//

        if(empty($all['password'])) {
            $all['password']='12345';
        }

        $customer = new CustomerModel();
        $row = $customer::where('mobile',$all['mobile'])->find();

        //如果不是新用户，就执行登录
        if(!empty($row)) {
            $login =new login();
            return $login->customer_login();
        }
            
        //return json(['code'=>0,'msg'=>'手机号码已存在,请改正后重试! '. $all['mobile']]);
        unset($all['verify_code']);
        $ct=date("Y-m-d H:i:s",time());
        $all['name']='游客_'.Common::randomString(6);
        $all['creater']  = 2;
        $all['create_time']  = $ct;
        $all['password']=substr(md5(trim($all['password']).'think'),0,32);
        $all['type']=1; //默认普通学员
        $all['status']=1;
        $all['fee_id']=0;
        $all['sex']=1;
        $all['dept_id']=1;
        $all['money_v']= md5($ct.'0');

        if(!empty($all['inviter'])){
            $inviter = $customer->where('mobile',$all['inviter'])->value('id');
            if($inviter) {
                $all['inviter']=$inviter;
            }else{
                return json(['code'=>0,'msg'=>'找不到邀请人资料，请确认手机号码是否正确！']);
            }
        }

        $login =new login();
        $all['token'] = $login->make_Token();
        $all['time_out'] = time() + 604800; //604800是七天
        
        $res =$customer->insertGetId($all);

        //分配记录处理
        $allocate_log=array(
            'customer_id'=>$res,
            'dept_id'=>1,
            'user_id'=>1,
            'memo'=>'小程序注册',
            'create_time'=>date('Y-m-d H:i:s')
        );
        Db::table('allocate_log')->insert($allocate_log);



        if($res) {
            return json(['code'=>1,'msg'=>'ok','token'=>$all['token'],'name'=>$all['name']]);
        }else{
            return json(['code'=>0,'msg'=>'Fail!']);
        }


        // return json(['code'=>0,'msg'=>'哦吼！']);
        // View::assign(['sys'=>Db::table('sys')->find(1)]);
        // return View::fetch('register');
    }


    //报名学车
    public function sign_up(){
        $all=Request::param();
        if(empty($all['token'])) return json(['code'=>0,'msg'=>'登录后才能报名哦!']);

        $token = new Token();
        $arr = $token->check_token($all['token']); 
        if($arr['code']<1){
            return json($arr);
        }
        
        $customer=$arr['customer'];
        if($customer['type']==2) return json(['code'=>0,'msg'=>'你已经是教练了哦!']);
        if($customer['fee_id']) return json(['code'=>0,'msg'=>'你已经报过名了哦!']);

        if(empty($all['name']) || empty($all['mobile']) || empty($all['id_card'])){
            return json(['code'=>0,'msg'=>'请填写姓名,手机,身份证号码！']);
        }
        if(empty($all['type'])){
            return json(['code'=>0,'msg'=>'请选择你想报名的驾照类型！']); 
        }

        //检测邀请人
        $inviter='';
        if(!empty($all['inviter'])){
            if($all['inviter']==$all['mobile']) return json(['code'=>0,'msg'=>'自己不能邀请自己哦！']);
            $inviter = $this->getOne($all['inviter']); 

            if(!$inviter['code']) return json($inviter);
            $inviter = $inviter['data']['id'];
        }

        $arr=array(
            'id'=>$customer['id'],
            'name'=>$all['name'],
            'id_card'=>$all['id_card'],
            'mobile'=>$all['mobile'],
            'fee_id'=>$all['type'],
            'area'=>$all['area'],
            'inviter'=>$inviter,
            'login_ip'=>$_SERVER['REMOTE_ADDR'],
            'sign_time'=>date('Y-m-d H:i:s')
        );

        $res =Db::table('customer')->update($arr);
        if($res){

            //短信通知
            if(Db::table('sys')->where('id',1)->value('sign_up_sms')==1){
                $sms =new Sms();
                $res = $sms->sign_up_sms($customer);
            }

            //系统消息提示
            $msg = array(
                'text' =>'新学员通过手机报名,驾照类型:'.$this->train_type[$all['type']],
                'img' =>'',
                'customer_id'=>$customer['id'],
                'create_time'=>date('Y-m-d H:i:s'),
                'status'=>1,
                'type'=>3
            );
            Db::table('msg')->insert($msg);

            return json(['code'=>1,'msg'=>'报名成功，请等待客服人员联系！']);
        }


        return json(['code'=>0,'msg'=>'不明原因失败，请联系技术人员!']);

    }

    //取消报名
    public function sign_clean(){
        $all=Request::param();
        if(empty($all['token'])) return json(['code'=>0,'msg'=>'Invalid token!']);

        $token = new Token();
        $arr = $token->check_token($all['token']); 
        if($arr['code']<1){
            return json($arr);
        }
        $row=$arr['customer'];

        $fee_id=$row['fee_id'];

        $row['fee_id']=''; //就是重新选驾照类型
        $row['fee_time']='';
        $res = Db::table('customer')->update($row);

        //消息
        if($res){
            $msg = array(
            'text' =>'学员取消报名,驾照类型:'.$this->train_type[$fee_id],
            'customer_id'=>$row['id'],
            'create_time'=>date('Y-m-d H:i:s'),
            'status'=>1,
            'type'=>3
            );
            Db::table('msg')->insert($msg);   
        }

        return json(['code'=>1,'msg'=>'报名已取消！']);

    }

    //我的报名
    public function my_sign(){
        $all=Request::param();
        if(empty($all['token'])) return json(['code'=>0,'msg'=>'Invalid token!']);

        $token = new Token();
        $arr = $token->check_token($all['token']); 
        if($arr['code']<1){
            return json($arr);
        }
        $row=$arr['customer'];
        if($row['type']==2){
            return json(['code'=>0,'msg'=>'你是教练！']);
        }

        //$row=Db::table('customer')->find(54);
        if($row['fee_id']){
            $row['fee_type']=$this->train_type[$row['fee_id']];
            $row['fee_status'] = $row['fee_time']>'0'?'yes':'no';

            $fee= Db::table('fee')->find($row['fee_id']);
            unset($fee['text']);
            $row['fee']=$fee;
        }
        return json(['code'=>1,'data'=>$row]);
    }



    //客户新增
    public function customer_add(){
        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index.php/login/index/target/admin");

        $all = Request::param();
        $type=!empty($all['type'])?$all['type']:'1,12,24,36,48';
        $view = $type==2?'trainer_add':'customer_add';        

        if(!empty($all['mobile']) && !empty($all['name'])){
            if(!empty($all['id'])) return 'ID重复!'.$this->back;  
            if(!$all['name']) return '无效的姓名!'.$this->back;

            $all['mobile']=trim($all['mobile']);
            $mobile = Common::is_mobile($all['mobile']);
            if(!$mobile) {
                return '手机号码不正确！'.$this->back;
            }

            $customer = new CustomerModel();
            $row = $customer::where('mobile',$all['mobile'])->find();
            if(!empty($row)) return '手机号码已存在!  ['. $all['mobile']."]".$this->back;

            if(strlen($all['id_card'])==18){
                $idc=substr($all['id_card'],6,8);
                $all['birth_date'] =substr($idc,0,4)."-".substr($idc,4,2)."-".substr($idc,6,2);
            }

            $ct=date("Y-m-d H:i:s");

            $all['creater']  = $uid;
            $all['level']= 1;
            $all['password'] = substr(md5("12345think"),0,32);
            $all['create_time']  = $ct;
            $all['status']=1;
            $all['money_v']=md5($ct.'0');

            $res =$customer->insert($all);

            $loc= 'location:/index.php/customer/index/type/';
            $loc.=($type==2)?'2':'';

            return header($loc);   
        }
        View::assign([
            'type'=>$this->type,
            'dept'=>$this->dept,
            'status'=>$this->status,
            'levels'=>$this->levels,
            'train_type'=>$this->train_type,
            't_levels'=>$this->t_levels
        ]);


        return View::fetch($view);
    }

    public function resetpwd($id=''){
        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index.php/login/target/admin");

        $all=Request::param();

        if(empty($all['id'])) return json_encode(['code'=>0,'msg'=>'invalid customer !']);
        $customer = new CustomerModel();

        $res = $customer->update(['id'=>$all['id'],'password'=>md5('12345think')]);
        return json(['code'=>1,'msg'=>"会员密码已初始化为：12345"]);
        //header("location:/index.php/user");
    }

    //客户端改密码
    public function resetpwd2(){
        $all=Request::param();

        if(empty($all['mobile']) ){
            return json(['code'=>0,'msg'=>'请输入你注册的手机号码！']);
        }

        $customer =Db::table('customer')->where('mobile',$all['mobile'])->find();
        if(!$customer){
            return json(['code'=>0,'msg'=>'你还没注册呢！']);
        }

        //----------短信验证码-----------------------------------//
        if(empty($all['verify_code']) || empty($all['password'])){//
            return json(['code'=>0,'msg'=>'请输入短信验证码及新密码！']);
        }

        $sess_vcode=Cache::get($all['mobile']);
        if(empty($sess_vcode)){
            return json(['code'=>0,'msg'=>'请先获取验证码！']);
        }

        if($all['verify_code']!=$sess_vcode) {
            return json(['code'=>0,'msg'=>'验证码错误！']);
        }
        //----------短信验证码------------------------------------//

        $customer['password'] = md5(trim($all['password']).'think');
        Db::table('customer')->update($customer);

        return json(['code'=>1,'msg'=>'密码已修改！']);

    }

    public function logout($target='index'){
        Session::delete('logonid');
        Session::delete('uid');
        Session::delete('uname');
        Session::delete('utype');
        return header("location:/index.php/login/customer_login");
    }


    //陪练教练上下线
    public function online(){
        $all=Request::param();
        if(empty($all['token'])) return json(['code'=>0,'msg'=>'Invalid token!']);

        if(empty($all['online']) || ($all['online']!=1 && $all['online']!=2)){
            return json(['code'=>0,'msg'=>'errorx!']);
        }

        $token = new Token();
        $arr = $token->check_token($all['token']); 
        if($arr['code']<1){
            return json($arr);
        }

        $customer=$arr['customer'];
        if($customer['type']!=2){
            return json(['code'=>0,'msg'=>'你不是教练，无需此操作！']);
        }

        $customer['online'] = $all['online'];
        $res =Db::table('customer')->save($customer);

        return json(['code'=>$res,'msg'=>'你已'.($all['online']==1?'上线，请留意陪驾单！':'下线,将不会收到陪驾单！')]);
        
    }


    //学员之“我的”
    public function aboutme(){
        $all=Request::param();
        if(empty($all['token'])) return json(['code'=>0,'msg'=>'Invalid token!']);

        $token = new Token();
        $arr = $token->check_token($all['token']); 
        if($arr['code']<1){
            return json($arr);
        }

        $customer=$arr['customer'];

        if(!empty($all['update'])){
            if(empty($all['name'])) return json(['code'=>0,'msg'=>'name??']);
            $customer['name'] = $all['name'];

            if(!empty($_FILES['file']['size'])){
                $file =$this->check_file();
                $customer['image'] =$file['msg'];
            }else{
                $customer['image']=$all['file'];
            }

            //halt($customer,$all);
            $res = Db::table('customer')->save($customer);
            return json(['code'=>$res,'msg'=>'ok!','data'=>$customer]);
        }

        return json(['code'=>1,'data'=>$customer]);

    }    


    //对输入的参数做一些检测
    private function input_check(&$all=[]){
            //手机号码检测
            $mobile = Common::is_mobile($all['mobile']); 

            if(!$mobile) {
                return ['code'=>0,'msg'=>'手机号码不正确！'];
            }
            $row=Db::table('customer')->where('mobile',$all['mobile'])->where('id','<>',$all['id'])->value('name');
            if($row){
                return ['code'=>0,'msg'=>'手机号码与:['.$row.'] 重复!'];
            }

            if(!empty($all['tel'])){
                $all['tel']=str_replace("，",',',strtoupper(str_replace(' ','',$all['tel'])));
            }

            if($_FILES['file']['size']>0){
                $files =Common::upload();
                
                if($files['code']){
                    $all['image']=$files['msg'];
                    return ['code'=>1];
                }else{
                    return ["code"=>0,'msg'=>"<h1>".$files['msg']."</h1>"];
                }


            }
            return ['code'=>1];
    }


    //上传文件检测
    private function check_file(){

        if($_FILES['file']['size']>0){
            $files =Common::upload();
            
            if($files['code']){
                //$all['image']=$files['msg'];
                return ['code'=>1];
            }else{
                return ["code"=>0,'msg'=>"<h1>".$files['msg']."</h1>"];
            }
        }
        return ['code'=>0,'msg'=>'no file post!'];
    }


    //我的推广
    public function my_invite(){
        $all=Request::param();
        if(empty($all['token'])){
            return json(['code'=>0,'msg'=>'需要token!']);
        }

        $token = new Token();
        $arr = $token->check_token($all['token']);
        if(!$arr['code']){
            return json($arr['msg']);
        }

        $me = $arr['customer'];
        $list = Db::query("select `id`,name,mobile,sex,create_time,status,fee_id from customer where inviter=? order by create_time",[$me['id']]);

        foreach($list as &$cust){
            $cust['status_name'] = $this->status_xy[$cust['status']];
            $cust['fee_id_name']=$this->train_type[$cust['fee_id']];
        }

        return json(['code'=>1,'msg'=>'count:'.count($list),'data'=>$list]);

    }

    //我的教练接口
    public function my_tors(){
        $all=Request::param();

        if(empty($all['type'])){
            return json(['code'=>0,'msg'=>'需要Type参数!(1/2)']);
        }
        $type = $all['type'];

        if(empty($all['token'])){
            return json(['code'=>0,'msg'=>'需要token!']);
        }

        $token = new Token();
        $arr = $token->check_token($all['token']);
        if(!$arr['code']){
            return json($arr['msg']);
        }
        $me = $arr['customer'];

        if($type!=2){
            //我的学员 
            $list = Db::query("select * from customer where  trainer=? order by create_time",[$me['id']]);
            foreach($list as &$st){
                $st['status_name'] = $this->status_xy[$st['status']];
                $st['sex'] = $st['sex']==1? '男':($st['sex']==2?'女':'');
            }
        }else{
            //我的教练
            $list = Db::query("select * from customer where id=? order by create_time",[$me['trainer']]);

            foreach($list as &$kv){
                $kv['train_type_name'] = $kv['type']==2 && $kv['tel']?$kv['tel']:'未选择';
                //查出绑定的教练车
                $ss= Db::table('car')->where('trainer_id',$kv['id'])->column('license');
                $kv['car_str']=implode(',',$ss);
                $kv['image'] = empty($kv['image'])?'/upload/logo.png':$kv['image'];

            }

        }

        return json(['code'=>1,'data'=>$list]);
    }


    //我的定期红包计划
    public function my_refund(){
        $all=Request::param();
        if(empty($all['token'])){
            return json(['code'=>0,'msg'=>'需要token!']);
        }        
        $token = new Token();
        $arr = $token->check_token($all['token']);
        if(!$arr['code']){
            return json($arr['msg']);
        }

        $me = $arr['customer'];

        if($me['type']<10){
            return json(['code'=>0,'msg'=>'你没有预定红包计划！']);
        }
        if($me['fee_time']<1){
            return json(['code'=>0,'msg'=>'你还没缴费学车，没有红包哦！']);
        }

        $list = Db::table('refund_plan')->where('customer_id',$me['id'])->select()->toArray();

        $td = date('Y-m-d');
        $msg='ok';

        foreach($list as &$plan){
            $plan['status_name'] = $plan['status']==1?'待发':'已发';
            //到期发放红包,状态未发的
            if($plan['status']==1 && $td>=$plan['plan_time']){
                $acc_log=array(
                    'type'=>4, //红包
                    'customer_id'=>$me['id'],
                    'dept_id'=>$me['dept_id'],
                    'money'=>100,
                    'memo'=>$plan['memo']."到期自动发放.",
                    'payment'=>'balance',
                    'creater'=>2,
                    'create_time'=>date('Y-m-d H:i:s'),
                    'check_by'=>2,
                    'check_time'=>date('Y-m-d H:i:s'),
                    'status'=>2
                ); 

                $res = Db::table('acc_log')->insert($acc_log);
                if($res){
                    Db::execute('update refund_plan set status=2 where id=?',[$plan['id']]);
                    Db::execute('update customer set money=money+? where id=?',[$plan['money'],$me['id']]);
                    $msg='今天系统给你发了一个红包！';
                }

            }

        }

        return json(['code'=>1,'data'=>$list,'msg'=>$msg]);

    }

    //改密码
    public function change_pwd(){
        $all=Request::param();
        if(empty($all['token'])){
            return json(['code'=>0,'msg'=>'请登录!']);
        }        
        $token = new Token();
        $arr = $token->check_token($all['token']);
        if(!$arr['code']){
            return json($arr['msg']);
        }

        $cust = $arr['customer']; //halt($cust);

        if(empty($all['pwd']) || empty($all['pwd_2'])){
            return json(['code'=>0,'msg'=>'密码错误!']);
        }

        $p =md5($all['pwd'].'think');
        if($p!= $cust['password']){
            return json(['code'=>0,'msg'=>'原密码错误！']);
        }        

        $name = $cust['name'];
        if(empty($all['name'])){
            $name = $all['name'];
        }

        $arr =array('id'=>$cust['id'],'name'=>$name,'password'=>md5($all['pwd_2'].'think')); 
        $res =Db::table('customer')->update($arr);


        if($res) return json(['code'=>1,'msg'=>'修改成功！']);

        return json(['code'=>0,'msg'=>'密码未修改！']);

    }

    //教练详情页
    public function customer_detail(){
        $all=Request::param();
        if(empty($all['id'])) return json(['code'=>0,'msg'=>'缺少必要参数:id']);

        $data=Db::table('customer')->find($all['id']);
        if(!$data) return json(['code'=>0,'msg'=>'没有资料!']);

        $assess = Db::table('assess')->where('to',$data['id'])->select()->toArray();
        foreach($assess as &$row){
            $row['from_name'] =Db::table('customer')->where('id',$row['from'])->column('name,image');

        }
        $data['assess'] = $assess;

        return json($data);


    }

}
